package com.whjk.core.security.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import com.whjk.core.security.uitls.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyMetaObjectHandler
 *
 * @author sai
 * @date 2020/8/12
 */
@Slf4j
@Component("myMetaObjectHandler")
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 在执行insert方法，会执行公共字段赋值
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime date = LocalDateTime.now();
        // Date date = new Date();
        String userName = "";
        if (null != SecurityUtils.getAuthentication() && null != SecurityUtils.getUser()) {
            userName = SecurityUtils.getUser().getName();
        }

        Object createUser = this.getFieldValByName("createUser", metaObject);
        if (createUser == null) {
            this.setFieldValByName("createUser", userName, metaObject);
        }
      /*  Object updateUser = this.getFieldValByName("updateUser", metaObject);
        if (updateUser == null) {
            this.setFieldValByName("updateUser", userName, metaObject);
        }*/

        Object createTime = this.getFieldValByName("createTime", metaObject);
        if (createTime == null) {
            this.setFieldValByName("createTime", date, metaObject);
        }
       /* Object updateTime = this.getFieldValByName("updateTime", metaObject);
        if (updateTime == null) {
            this.setFieldValByName("updateTime", date, metaObject);
        }*/
    }

    /**
     * 在执行update方法，会执行公共字段赋值
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime date = LocalDateTime.now();
        // Date date = new Date();
        String userName = "";
        if (null != SecurityUtils.getAuthentication() && null != SecurityUtils.getUser()) {
            userName = SecurityUtils.getUser().getName();
        }
        this.setFieldValByName("updateTime", date, metaObject);
        this.setFieldValByName("updateUser", userName, metaObject);

    }

}
